package br.com.basili.hibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class ConexaoHibernate 
{
  public static final SessionFactory sessionFactory = buildSessionFactory();
  public static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();  

  public ConexaoHibernate() {  
  }  

  
  private static SessionFactory buildSessionFactory() {
    try {
        AnnotationConfiguration cfg = new AnnotationConfiguration();
        cfg.configure("hibernate.cfg.xml");
        return cfg.buildSessionFactory();
    } catch (Throwable e) {
        System.out.println("Criacao inicial do objeto SessionFactory falhou. Erro: " + e);
        e.printStackTrace();
        throw new ExceptionInInitializerError(e);
    }
}

  public static Session getInstance(){  
      Session session = (Session) threadLocal.get();  
      if (session == null) {  
          session = sessionFactory.openSession();  
          threadLocal.set(session);  
      }  
      return session;  
  }  		
}
